from flask import Flask, render_template
import pandas as pd
from datetime import datetime

app = Flask(__name__)

def load_data():
    df = pd.read_csv(CSV_FILE)
    df['日期'] = pd.to_datetime(df['日期'])
    return df

@app.route('/')
def index():
    df = load_data()
    # 获取每个用户的最新数据，包括用户ID和用户名
    latest_data = df.loc[df.groupby('用户ID')['日期'].idxmax()]
    users = latest_data[['用户ID', '掘金用户名']].to_dict('records')
    return render_template('index.html', users=users)

@app.route('/user/<user_id>')
def user_chart(user_id):
    df = load_data()
    # 打印 user_data 的内容
    # 把user_id转成数值
    user_id = int(user_id)

    # print(user_id)
    user_data = df[df['用户ID'] == user_id].sort_values('日期')
    # print(user_data)

    if user_data.empty:
        return {'dates': [], 'values': [], 'username': ''}
    dates = user_data['日期'].dt.strftime('%Y-%m-%d').tolist()
    values = user_data['掘力值'].tolist()
    username = user_data['掘金用户名'].iloc[-1]  # 获取最新的用户名
    return {'dates': dates, 'values': values, 'username': username}


@app.route('/bottom10')
def bottom10():
    df = load_data()
    # 获取每个用户的最新掘力值
    latest_data = df.loc[df.groupby('用户ID')['日期'].idxmax()]
    # 按掘力值升序排序并取后10名
    bottom10_users = latest_data.sort_values(by='掘力值', ascending=True).head(10)

    # 处理用户名，将前3个字符替换为**
    result = []
    for _, row in bottom10_users.iterrows():
        username = row['掘金用户名']
        if len(username) > 3:
            username = '**' + username[3:]
        result.append({
            '掘金用户名': username,
            '掘力值': row['掘力值'],
            '用户ID': row['用户ID']
        })
    return result


@app.route('/top10')
def top10():
    df = load_data()
    # 获取每个用户的最新掘力值
    latest_data = df.loc[df.groupby('用户ID')['日期'].idxmax()]
    # 按掘力值降序排序并取前10
    top10_users = latest_data.sort_values(by='掘力值', ascending=False).head(10)
    # 转换为字典列表，方便前端使用
    result = top10_users[['掘金用户名', '掘力值','用户ID']].to_dict(orient='records')
    return result

@app.route('/average')
def average_score():
    df = load_data()
    # 获取每个用户的最新掘力值
    latest_data = df.loc[df.groupby('掘金用户名')['日期'].idxmax()]
    # 计算平均分
    avg_score = latest_data['掘力值'].mean()
    return {'average': round(avg_score, 2)}


@app.route('/overview')
def overview():
    df = load_data()
    # 获取每个用户的最新掘力值
    latest_data = df.loc[df.groupby('用户ID')['日期'].idxmax()]

    # 1. 当前用户总数
    total_users = int(len(latest_data))

    # 2. 平均分
    avg_score = float(latest_data['掘力值'].mean())

    # 3. 最高的前3名
    top3 = latest_data.nlargest(3, '掘力值')[['掘金用户名', '掘力值']]
    top3_list = []
    for _, row in top3.iterrows():
        top3_list.append({
            '掘金用户名': str(row['掘金用户名']),
            '掘力值': int(row['掘力值'])
        })

    # 4. 计算比上次统计有进步的人数
    improved_count = 0
    for username in df['掘金用户名'].unique():
        user_data = df[df['掘金用户名'] == username].sort_values('日期')
        if len(user_data) >= 2:
            if int(user_data.iloc[-1]['掘力值']) > int(user_data.iloc[-2]['掘力值']):
                improved_count += 1

    # 5. 最近一次统计中分数增加最多的前3个ID
    score_changes = []
    for username in df['掘金用户名'].unique():
        user_data = df[df['掘金用户名'] == username].sort_values('日期')
        if len(user_data) >= 2:
            change = int(user_data.iloc[-1]['掘力值']) - int(user_data.iloc[-2]['掘力值'])
            if change > 0:
                score_changes.append({
                    '掘金用户名': str(username),
                    '增长值': change
                })

    top3_improvements = sorted(score_changes, key=lambda x: x['增长值'], reverse=True)[:3]

    return {
        'total_users': total_users,
        'average_score': round(avg_score, 2),
        'top3': top3_list,
        'improved_count': improved_count,
        'top3_improvements': top3_improvements
    }


@app.route('/improved')
def improved_students():
    df = load_data()
    improved_students = []

    # 对每个用户检查是否持续进步
    for user_id in df['用户ID'].unique():
        user_data = df[df['用户ID'] == user_id].sort_values('日期')
        # 只取最近5次记录
        recent_data = user_data.tail(5)

        if len(recent_data) < 2:  # 至少需要两次记录
            continue

        # 检查最近5次每次统计是否都有10分以上的增加
        is_improved = True
        for i in range(1, len(recent_data)):
            if recent_data.iloc[i]['掘力值'] - recent_data.iloc[i - 1]['掘力值'] < 10:
                is_improved = False
                break

        if is_improved:
            # 获取该用户的最新数据
            latest = recent_data.iloc[-1]
            improved_students.append({
                '掘金用户名': str(latest['掘金用户名']),
                '最新掘力值': int(latest['掘力值']),
                '用户ID': str(latest['用户ID']),
                '增长次数': int(len(recent_data) - 1)
            })

    # 按增长次数降序排序
    improved_students.sort(key=lambda x: x['增长次数'], reverse=True)
    return improved_students


def start_app(csv_file='4'):
    global CSV_FILE
    CSV_FILE = 'results/result_' + csv_file + '.csv'
    app.run(host='0.0.0.0', port=5000,debug=True)


if __name__ == '__main__':
    start_app('1')
